package com.qdxht.dispenser.service;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.util.Log;
import com.qdxht.daemons.IWatchdogService;

import timber.log.Timber;

/**
 * 看门狗客户端，示例第三方应用如何使用看门狗服务
 */
public class WatchdogClient {
    private static final String TAG = "WatchdogClient";
    
    private final Context context;
    private final String packageName;
    private final String activityName;
    
    private IWatchdogService watchdogService;
    private boolean isBound = false;
    private boolean isMonitoring = false;
    
    private final Handler handler = new Handler(Looper.getMainLooper());
    private final Runnable heartbeatRunnable = new Runnable() {
        @Override
        public void run() {
            sendHeartbeat();
            // 每分钟发送一次心跳,实际30s
            handler.postDelayed(this, 30 * 1000);
        }
    };
    
    // 服务连接回调
    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 使用AIDL接口获取服务代理对象
            watchdogService = IWatchdogService.Stub.asInterface(service);
            isBound = true;
            Timber.tag(TAG).d( "已连接到看门狗服务");
            
            // 连接成功后立即开始监测
            if (startMonitoring()) {
                // 开始发送心跳
                handler.post(heartbeatRunnable);
            }
        }
        
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Timber.tag(TAG).d( "与看门狗服务断开连接");
            watchdogService = null;
            isBound = false;
            isMonitoring = false;
            
            // 停止心跳
            handler.removeCallbacks(heartbeatRunnable);
            
            // 尝试重新绑定服务
            bindWatchdogService();
        }
    };
    
    /**
     * 构造函数
     *
     * @param context 应用上下文
     * @param activityName 主Activity的完整类名
     */
    public WatchdogClient(Context context, String activityName) {
        this.context = context;
        this.packageName = context.getPackageName();
        this.activityName = activityName;
    }
    
    /**
     * 开始使用看门狗服务
     */
    public boolean connect() {
        return bindWatchdogService();
    }
    
    /**
     * 停止使用看门狗服务
     */
    public void disconnect() {
        // 停止监测
        stopMonitoring();
        
        // 停止心跳
        handler.removeCallbacks(heartbeatRunnable);
        
        // 解绑服务
        if (isBound) {
            try {
                context.unbindService(serviceConnection);
                isBound = false;
            } catch (Exception e) {
                Timber.tag(TAG).e( "解绑服务失败:%s", e);
            }
        }
    }
    
    /**
     * 绑定看门狗服务
     */
    private boolean bindWatchdogService() {
        try {
            Intent intent = new Intent();
            // 指定服务的包名和类名
            intent.setComponent(new ComponentName(
                    "com.qdxht.daemons", 
                    "com.qdxht.daemons.WatchdogService"));
            
            return context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
        } catch (Exception e) {
            Timber.tag(TAG).e( "绑定服务失败:%s", e);
            return false;
        }
    }
    
    /**
     * 开始监测
     */
    private boolean startMonitoring() {
        if (!isBound || watchdogService == null) {
            Timber.tag(TAG).e( "服务未连接，无法开始监测");
            return false;
        }
        
        try {
            // 直接调用AIDL接口方法
            boolean result = watchdogService.startMonitoring(packageName, activityName);
            if (result) {
                isMonitoring = true;
                Timber.tag(TAG).i( "成功开始监测");
            } else {
                Timber.tag(TAG).e( "开始监测失败");
            }
            return result;
        } catch (RemoteException e) {
            Timber.tag(TAG).e( "远程调用开始监测方法异常:%s", e);
            return false;
        }
    }
    
    /**
     * 发送心跳
     */
    public boolean sendHeartbeat() {
        if (!isBound || watchdogService == null) {
            Timber.tag(TAG).e( "服务未连接，无法发送心跳");
            return false;
        }
        
        if (!isMonitoring) {
            Timber.tag(TAG).e( "未开始监测，无法发送心跳");
            return false;
        }
        
        try {
            // 直接调用AIDL接口方法
            boolean result = watchdogService.heartbeat(packageName);
            if (result) {
                Timber.tag(TAG).d( "成功发送心跳");
            } else {
                Timber.tag(TAG).e( "发送心跳失败");
            }
            return result;
        } catch (RemoteException e) {
            Timber.tag(TAG).e( "远程调用心跳方法异常:%s", e);
            return false;
        }
    }
    
    /**
     * 停止监测
     */
    private boolean stopMonitoring() {
        if (!isBound || watchdogService == null) {
            Timber.tag(TAG).e( "服务未连接，无法停止监测");
            return false;
        }
        
        if (!isMonitoring) {
            return true;
        }
        
        try {
            // 直接调用AIDL接口方法
            boolean result = watchdogService.stopMonitoring(packageName);
            if (result) {
                isMonitoring = false;
                Timber.tag(TAG).i( "成功停止监测");
            } else {
                Timber.tag(TAG).e( "停止监测失败");
            }
            return result;
        } catch (RemoteException e) {
            Timber.tag(TAG).e( "远程调用停止监测方法异常:%s", e);
            return false;
        }
    }
} 